<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\BaseController;
use support\exception\BusinessException;
use support\Redis;

class BaseApi extends BaseController
{
    /**
     * 获取当前登录用户ID
     * @param bool $throwException 当获取不到userId时是否抛出异常，默认为false返回null
     * @return string|null
     */
    protected function getUserId(bool $throwException = false): ?string
    {
        // 获取请求头中的token
        $token = request()->header('authorization');

        if (!$token) {
            if ($throwException) {
                throw new BusinessException('缺少请求token', 2001);
            }

            return null;
        }

        // 从Redis获取用户ID
        $userId = Redis::get($token);
        if (empty($userId)) {
            if ($throwException) {
                throw new BusinessException('登录已过期，请重新登录', 2001);
            }

            return null;
        }
        
        return $userId;
    }
}